/*
 *    Copyright 2008-2010 Simone Tripodi
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.testnguice.inject;

import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.IObjectFactory;
import org.testng.ITestContext;
import org.testng.annotations.ObjectFactory;
import org.testng.internal.ObjectFactoryImpl;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;

/**
 * Light injector implementation for TestNG, based on google-guice.
 *
 * @author Simone Tripodi
 * @version $Id: AbstractGuiceObjectFactory.java 243 2010-06-29 10:46:02Z simone.tripodi $
 */
public abstract class AbstractGuiceObjectFactory implements IObjectFactory {

    /**
     * The serial version UID.
     */
    private static final long serialVersionUID = 1L;

    /**
     * This class logger.
     */
    private final Log log = LogFactory.getLog(this.getClass());

    /**
     * The default TestNG provided implementation of {@link IObjectFactory}.
     */
    private final ObjectFactoryImpl creator = new ObjectFactoryImpl();

    /**
     * The Injector used to inject dependencies into Test Case classes.
     */
    private final Injector injector;

    /**
     * Instantiates a new ObjectFactory using the specified modules.
     *
     * @param modules the modules containing bindings and configurations
     * @deprecated
     */
    @Deprecated
    public AbstractGuiceObjectFactory(Module...modules) {
        throw new IllegalStateException("Called constructor has been deprecated");
    }

    /**
     * Instantiates a new ObjectFactory relying on Google Guice.
     */
    public AbstractGuiceObjectFactory() {
        this.injector = Guice.createInjector(this.createTestContext());
    }

    /**
     * Builds the test module list.
     *
     * @return the test module list.
     */
    protected abstract List<Module> createTestContext();

    /**
     * {@inheritDoc}
     */
    public final Object newInstance(@SuppressWarnings("unchecked") final Constructor constructor, final Object... args) {
        if (this.log.isDebugEnabled()) {
            this.log.debug("Creating new object of type '"
                    + constructor.getDeclaringClass().getName()
                    + "' using constructor '"
                    + constructor
                    + "' with arguments "
                    + Arrays.deepToString(args));
        }

        Object obj = this.creator.newInstance(constructor, args);

        if (this.log.isDebugEnabled()) {
            this.log.debug("Created object of type '"
                    + obj.getClass().getName()
                    + "', injecting dependencies..");
        }

        Injector derivedInjector = this.injector.createChildInjector(new MockModule(obj.getClass()));
        derivedInjector.injectMembers(obj);

        if (this.log.isDebugEnabled()) {
            this.log.debug("Dependencies successfully injected in object of type '"
                    + obj.getClass().getName()
                    + "'");
        }

        return obj;
    }

    @ObjectFactory
    public final IObjectFactory init(final ITestContext context) {
        return this;
    }

}
